package com.lesserpand.springcloudalibabacore.test.controller;

import com.lesserpand.springcloudalibabacore.config.redis.redissonlock.service.SkillService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author bailuo
 * @version 2.0
 * @Description 由于使用redisson实现分布式锁非常简单，这里直接写一个小栗子即可
 * @Date Created in 2019/1/14 14:30
 */
@RestController
@RequestMapping("/redisson-lock")
public class RedissonLockTestController {

    @Autowired
    private SkillService skillService;

    /**
     * 手动初始化抢购数据
     *
     * @param proId
     * @return
     */
    @PutMapping(value = "/init-skill")
    public String initSkill(@RequestParam("proId") Long proId, @RequestParam("skillId") Long skillId, @RequestParam("num") String num) {
        return skillService.initSkill(proId, skillId, num);
    }

    /**
     * 模拟抢购
     *
     * @param userId
     * @param proId
     * @return
     */
    @GetMapping(value = "/skill")
    public String skill(@RequestParam("userId") Long userId, @RequestParam("skillId") Long skillId, @RequestParam("proId") Long proId) {
        for (int i = 0; i < 20; i++) {
            new Thread(() -> {
                skillService.skill(2L, skillId, proId);
                try {
                    Thread.sleep(100L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }
        return skillService.skill(userId, skillId, proId);
    }

}
